package org.dromara.hotel.service.impl;

import org.dromara.common.core.utils.BeanUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hotel.mapper.TerHotelRoomsMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.dromara.hotel.domain.bo.TerPricingRuleBo;
import org.dromara.hotel.domain.vo.TerPricingRuleVo;
import org.dromara.hotel.domain.TerPricingRule;
import org.dromara.hotel.mapper.TerPricingRuleMapper;
import org.dromara.hotel.service.ITerPricingRuleService;
import org.dromara.hotel.util.RuleEngineUtil;

import java.time.LocalDate;
import java.util.*;

/**
 * 酒店价格规则Service业务层处理
 *
 * @author xch
 * @date 2025-06-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class TerPricingRuleServiceImpl implements ITerPricingRuleService {

    private final TerPricingRuleMapper baseMapper;
    private final TerHotelRoomsMapper roomTypeMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(TerPricingRuleServiceImpl.class);
    /**
     * 查询酒店价格规则
     *
     * @param id 主键
     * @return 酒店价格规则
     */
    @Override
    public TerPricingRuleVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询酒店价格规则列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 酒店价格规则分页列表
     */
    @Override
    public TableDataInfo<TerPricingRuleVo> queryPageList(TerPricingRuleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TerPricingRule> lqw = buildQueryWrapper(bo);
        Page<TerPricingRuleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的酒店价格规则列表
     *
     * @param bo 查询条件
     * @return 酒店价格规则列表
     */
    @Override
    public List<TerPricingRuleVo> queryList(TerPricingRuleBo bo) {
        LambdaQueryWrapper<TerPricingRule> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TerPricingRule> buildQueryWrapper(TerPricingRuleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TerPricingRule> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TerPricingRule::getId);
        lqw.eq(bo.getRoomId() != null, TerPricingRule::getRoomId, bo.getRoomId());
        lqw.eq(StringUtils.isNotBlank(bo.getRuleType()), TerPricingRule::getRuleType, bo.getRuleType());
        lqw.eq(bo.getStartDate() != null, TerPricingRule::getStartDate, bo.getStartDate());
        lqw.eq(bo.getEndDate() != null, TerPricingRule::getEndDate, bo.getEndDate());
        lqw.eq(StringUtils.isNotBlank(bo.getConditionJson()), TerPricingRule::getConditionJson, bo.getConditionJson());
        lqw.eq(StringUtils.isNotBlank(bo.getFormula()), TerPricingRule::getFormula, bo.getFormula());
        lqw.eq(bo.getPriority() != null, TerPricingRule::getPriority, bo.getPriority());
        lqw.eq(bo.getIsActive() != null, TerPricingRule::getIsActive, bo.getIsActive());
        return lqw;
    }

    /**
     * 新增酒店价格规则
     *
     * @param bo 酒店价格规则
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TerPricingRuleBo bo) {
        TerPricingRule add = BeanUtils.toBean(bo, TerPricingRule.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改酒店价格规则
     *
     * @param bo 酒店价格规则
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TerPricingRuleBo bo) {
        TerPricingRule update = MapstructUtils.convert(bo, TerPricingRule.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TerPricingRule entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除酒店价格规则信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
    @Override
//    @Cacheable(value = "priceCache", key = "#roomTypeId+'-'+#date")
    public Integer getDailyPrice(Long roomTypeId, LocalDate date , List<TerPricingRule> activeRules) {
        // 1. 实时规则计算
        Integer dynamicPrice = calculateByRules(roomTypeId, date , activeRules);
        if (dynamicPrice != null) return dynamicPrice;
        // 2. 回退基础价格
        return roomTypeMapper.selectById(roomTypeId).getPrice();
    }

    private Integer calculateByRules(Long roomTypeId, LocalDate date ,List<TerPricingRule> activeRules) {


        return activeRules.stream()
            .sorted(Comparator.comparingInt(TerPricingRule::getPriority).reversed())
            .findFirst()
            .map(rule -> applyRule(rule, roomTypeId, date))
            .orElse(null);
    }

    private Integer applyRule(TerPricingRule rule, Long roomTypeId, LocalDate date) {
        Integer base = roomTypeMapper.selectById(roomTypeId).getPrice();
        Map<String, Number> params = new HashMap<>();
        params.put("base", base);
        params.put("date", date.getDayOfMonth());
        LOGGER.info(roomTypeId+"："+base);
        if(isDateInRange(date,rule.getStartDate(),rule.getEndDate())){
            if (rule.getConditionJson() != null) {
                if (RuleEngineUtil.evaluate(rule.getConditionJson(), params)) {
                    return (int) RuleEngineUtil.evaluateExpression(rule.getFormula(), params);
                } else {
                    return base;
                }
            }else{
                return (int) RuleEngineUtil.evaluateExpression(rule.getFormula(), params);
            }
        }else{
            return base;
        }
    }
    public static boolean isDateInRange(LocalDate target, LocalDate start, LocalDate end) {
        LocalDate effectiveStart = start.isBefore(end) ? start : end;
        LocalDate effectiveEnd = start.isBefore(end) ? end : start;
        return (!target.isBefore(effectiveStart)) && (!target.isAfter(effectiveEnd));
    }
}
